<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Linux安全," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;一个恐怖的例子： &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;注入式攻击的详细解释SQL下面我们将以一个简单的用户登陆为例，结合代码详细解释一下SQL注入式攻击，与及他的防范措施。对于一个简单的用户登陆可能的代码如下： 1234567891011121">
<meta name="keywords" content="Linux安全">
<meta property="og:type" content="article">
<meta property="og:title" content="防止SQL注入">
<meta property="og:url" content="https://hcldirgit.github.io/2017/09/03/Linux安全/12. 防止SQL注入/index.html">
<meta property="og:site_name" content="失落的乐章">
<meta property="og:description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;一个恐怖的例子： &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;注入式攻击的详细解释SQL下面我们将以一个简单的用户登陆为例，结合代码详细解释一下SQL注入式攻击，与及他的防范措施。对于一个简单的用户登陆可能的代码如下： 1234567891011121">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-09-01T08:54:37.426Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="防止SQL注入">
<meta name="twitter:description" content="&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;一个恐怖的例子： &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;注入式攻击的详细解释SQL下面我们将以一个简单的用户登陆为例，结合代码详细解释一下SQL注入式攻击，与及他的防范措施。对于一个简单的用户登陆可能的代码如下： 1234567891011121">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hcldirgit.github.io/2017/09/03/Linux安全/12. 防止SQL注入/"/>





  <title>防止SQL注入 | 失落的乐章</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '85*****1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?87980c**************99ec5e26fb5";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>











  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">失落的乐章</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术面前，永远都是学生。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-message">
          <a href="/message" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-external-link"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://hcldirgit.github.io/2017/09/03/Linux安全/12. 防止SQL注入/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="失落的乐章">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/0.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="失落的乐章">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">防止SQL注入</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-03T02:04:46+08:00">
                2017-09-03
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一个恐怖的例子：</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;注入式攻击的详细解释SQL下面我们将以一个简单的用户登陆为例，结合代码详细解释一下SQL注入式攻击，与及他的防范措施。对于一个简单的用户登陆可能的代码如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">try</div><div class="line">&#123;</div><div class="line">　string strUserName = this.txtUserName.Text;</div><div class="line">　string strPwd = this.txtPwd.Text;</div><div class="line">　string strSql = <span class="string">"select * from userinfo where UserName='"</span> + strUserName + <span class="string">"' and Password='"</span> + strPwd + <span class="string">"'"</span>;</div><div class="line">　SqlConnection objDbConn = new SqlConnection(<span class="string">"数据库连接字符串"</span>);</div><div class="line">　SqlDataAdapter objAdapter = new SqlDataAdapter(strSql,objDbConn);</div><div class="line">　DataSet objDataSet = null;</div><div class="line">　objAdapter.Fill(objDataSet);//TODO 对获取的数据进行判断。</div><div class="line">&#125;</div><div class="line">catch (System.Exception e)</div><div class="line">&#123;</div><div class="line">　this.lblMsg.Text = e.Message;</div><div class="line">　this.lblMsg.Visible = <span class="literal">true</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;在上面这段代码中，如果用户的输入是正常的用户名和密码的话，那么执行都会比较正常，但是，假如输入用户名的时候，输入的是“johny’–”的话，在 SQLServer里面执行的语句将会是“select * from userinfo where UserName=’johny’–‘ and Password=’密码’”，只要数据库中存在johny这个用户的话，那么不管密码是什么，语句都能够执行成功，并且能够顺利通过登陆。还 有更加厉害的，我们知道SQLServer里面有一些系统的存储过程，能够执行操作系统的很多命令，比如xp_cmdshell，假如上面用户登陆的时 候，用户名部分输入的是“johny’ exec xp_cmdshell ‘format d:/s’–”，大家想想一下后果是什么？有恶意的用户，只要把’format d:/s’这个命令稍加改造就能够做很多不合法的事情。</p>
<h2 id="NET防SQL注入方法"><a href="#NET防SQL注入方法" class="headerlink" title=".NET防SQL注入方法"></a>.NET防SQL注入方法</h2><h3 id="1-利用SqlCommand传参数的方法："><a href="#1-利用SqlCommand传参数的方法：" class="headerlink" title="1.利用SqlCommand传参数的方法："></a>1.利用SqlCommand传参数的方法：</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">string strSQL=<span class="string">"SELECT * FROM [user] WHERE user_id=@id"</span>;</div><div class="line">SqlCommand cmd = new SqlCommand();</div><div class="line">cmd.CommandText = strSQL;</div><div class="line">cmd.Parameters.Add(<span class="string">"@id"</span>,SqlDbType.VarChar,20).Value=Request[<span class="string">"id"</span>].ToString();</div></pre></td></tr></table></figure>
<h3 id="2-过滤禁止运行法："><a href="#2-过滤禁止运行法：" class="headerlink" title="2.过滤禁止运行法："></a>2.过滤禁止运行法：</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">/// &lt;summary&gt;</div><div class="line">/// 过滤SQL语句,防止注入</div><div class="line">/// &lt;/summary&gt;</div><div class="line">/// &lt;param name=<span class="string">"strSql"</span>&gt;&lt;/param&gt;</div><div class="line">/// &lt;returns&gt;0 - 没有注入, 1 - 有注入 &lt;/returns&gt;</div><div class="line">public int filterSql(string sSql)</div><div class="line">&#123; </div><div class="line"> int srcLen, decLen = 0;</div><div class="line"> sSql = sSql.ToLower().Trim();</div><div class="line"> srcLen = sSql.Length;</div><div class="line"> sSql = sSql.Replace(<span class="string">"exec"</span>, <span class="string">""</span>);</div><div class="line"> sSql = sSql.Replace(<span class="string">"delete"</span>, <span class="string">""</span>);</div><div class="line"> sSql = sSql.Replace(<span class="string">"master"</span>, <span class="string">""</span>);</div><div class="line"> sSql = sSql.Replace(<span class="string">"truncate"</span>, <span class="string">""</span>);</div><div class="line"> sSql = sSql.Replace(<span class="string">"declare"</span>, <span class="string">""</span>);</div><div class="line"> sSql = sSql.Replace(<span class="string">"create"</span>, <span class="string">""</span>);</div><div class="line"> sSql = sSql.Replace(<span class="string">"xp_"</span>, <span class="string">"no"</span>);</div><div class="line"> decLen = sSql.Length;</div><div class="line"> <span class="keyword">if</span> (srcLen == decLen) <span class="built_in">return</span> 0; <span class="keyword">else</span> <span class="built_in">return</span> 1; </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="3-存储过程"><a href="#3-存储过程" class="headerlink" title="3.存储过程"></a>3.存储过程</h3><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;js版的防范SQL注入式攻击代码：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">&lt;script language=<span class="string">"javascript"</span>&gt;</div><div class="line">&lt;!--</div><div class="line">var url = location.search;</div><div class="line">var re=/^\?(.*)(select%20|insert%20|delete%20from%20|count\(|drop%20table|update%20truncate%20|asc\(|mid\(|char\(|xp_cmdshell|<span class="built_in">exec</span>%20master|net%20localgroup%20administrators|\<span class="string">"|:|net%20user|\|%20or%20)(.*)$/gi;</span></div><div class="line"><span class="string">var e = re.test(url);</span></div><div class="line"><span class="string">if(e) &#123;</span></div><div class="line"><span class="string"> alert("</span>地址中含有非法字符～<span class="string">");</span></div><div class="line"><span class="string"> location.href="</span>error.asp<span class="string">";</span></div><div class="line"><span class="string">&#125;</span></div><div class="line"><span class="string">//--&gt;</span></div><div class="line"><span class="string">&lt;script&gt;</span></div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Linux安全/" rel="tag"># Linux安全</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/03/Linux安全/11. xss攻击入门/" rel="next" title="xss攻击入门">
                <i class="fa fa-chevron-left"></i> xss攻击入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/03/Linux安全/14. 文件系统安全/" rel="prev" title="文件系统安全">
                文件系统安全 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/0.png"
               alt="失落的乐章" />
          <p class="site-author-name" itemprop="name">失落的乐章</p>
           
              <p class="site-description motion-element" itemprop="description">失落的乐章的Blog</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">627</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hcldirgit" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#NET防SQL注入方法"><span class="nav-number">1.</span> <span class="nav-text">.NET防SQL注入方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-利用SqlCommand传参数的方法："><span class="nav-number">1.1.</span> <span class="nav-text">1.利用SqlCommand传参数的方法：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-过滤禁止运行法："><span class="nav-number">1.2.</span> <span class="nav-text">2.过滤禁止运行法：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-存储过程"><span class="nav-number">1.3.</span> <span class="nav-text">3.存储过程</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">失落的乐章</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
